package org.example.bean;

import java.util.Properties;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.example.exception.DataSourceInitFailedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.orm.jpa.JpaDialect;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 手动配置自己的DataSource, 不使用spring默认
 */
//@Configuration
//public class DataSourceConfig {
//    private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceConfig.class);
//    private static final String DRIVER_CLASS = "org.example.datasource.driver-class";
//    private static final String JDBC_URL = "org.example.datasource.url";
//    private static final String USER = "org.example.datasource.username";
//    private static final String PASSWORD = "org.example.datasource.password";
//    private static final String CHECKOUT_TIMEOUT = "org.example.datasource.checkout-timeout";
//    private static final String INITIAL_POOL_SIZE = "org.example.datasource.initial-pool-size";
//    private static final String MIN_POOL_SIZE = "org.example.datasource.min-pool-size";
//    private static final String MAX_POOL_SIZE = "org.example.datasource.max-pool-size";
//    private static final String MAX_IDLE_TIME = "org.example.datasource.max-idle-time";
//    private static final String IDLE_CONNECTION_TEST_PERIOD = "org.example.datasource.idle-connection-test-period";
//    @Autowired
//    private Environment environment;
//
//    /**
//     * 返回spring注入的datasource
//     * 直接使用environment加载为局部变量, 随垃圾收集清理掉这些变量, 不使用ServerConfig进行缓存.
//     *
//     * @return DataSource
//     */
//    @Bean
//    @SuppressWarnings("all")    //  配置文件一定有值, 屏蔽空指针告警
//    public DataSource dataSource() throws DataSourceInitFailedException {
//        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//        //  JDBC配置
//        String driverClass = environment.getProperty(DRIVER_CLASS);
//        String jdbcUrl = environment.getProperty(JDBC_URL);
//        String user = environment.getProperty(USER);
//        String password = environment.getProperty(PASSWORD);
//        //  C3P0连接池配置
//        int checkoutTimeout = Integer.parseInt(environment.getProperty(CHECKOUT_TIMEOUT));
//        int initialPoolSize = Integer.parseInt(environment.getProperty(INITIAL_POOL_SIZE));
//        int minPoolSize = Integer.parseInt(environment.getProperty(MIN_POOL_SIZE));
//        int maxPoolSize = Integer.parseInt(environment.getProperty(MAX_POOL_SIZE));
//        int maxIdleTime = Integer.parseInt(environment.getProperty(MAX_IDLE_TIME));
//        int acquireIncrement = Integer.parseInt(environment.getProperty(IDLE_CONNECTION_TEST_PERIOD));
//        int idleConnectionTestPeriod = Integer.parseInt(environment.getProperty(IDLE_CONNECTION_TEST_PERIOD));
//
//        try {
//            comboPooledDataSource.setDriverClass(driverClass);
//            comboPooledDataSource.setJdbcUrl(jdbcUrl);
//            comboPooledDataSource.setUser(user);
//            comboPooledDataSource.setPassword(password);
//
//            comboPooledDataSource.setCheckoutTimeout(checkoutTimeout);
//            comboPooledDataSource.setInitialPoolSize(initialPoolSize);
//            comboPooledDataSource.setMinPoolSize(minPoolSize);
//            comboPooledDataSource.setMaxPoolSize(maxPoolSize);
//            comboPooledDataSource.setMaxIdleTime(maxIdleTime);
//            comboPooledDataSource.setIdleConnectionTestPeriod(idleConnectionTestPeriod);
//        } catch (Exception e) {
//            LOGGER.error("init dataSource failed.", e);
//            throw new DataSourceInitFailedException("init dataSource failed!", e);
//        }
//
//        return comboPooledDataSource;
//    }
//
//    /**
//     * entityManagerFactory
//     *
//     * @return LocalContainerEntityManagerFactoryBean
//     */
//    @Bean
//    public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws DataSourceInitFailedException {
//        LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
//        entityManagerFactory.setDataSource(dataSource());
//        //  扫描包下所有实体类
//        entityManagerFactory.setPackagesToScan("org.example");
//
//        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
//        vendorAdapter.setDatabase(Database.MYSQL);
//        vendorAdapter.setShowSql(false);
//        vendorAdapter.setGenerateDdl(true);
//        entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
//        entityManagerFactory.setJpaProperties(jpaProperties());
//
//        return entityManagerFactory;
//    }
//
//    /**
//     * transactionManager
//     *
//     * @param entityManagerFactory entityManagerFactory
//     * @return JpaTransactionManager
//     */
//    @Bean
//    public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
//        JpaTransactionManager transactionManager = new JpaTransactionManager();
//        transactionManager.setEntityManagerFactory(entityManagerFactory);
//        JpaDialect jpaDialect = new HibernateJpaDialect();
//        //  设置JPA方言
//        transactionManager.setJpaDialect(jpaDialect);
//        return transactionManager;
//    }
//
//    private Properties jpaProperties() {
//        Properties properties = new Properties();
//        properties.setProperty("hibernate.hbm2ddl.auto", "update");
//        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL55Dialect");
//        properties.setProperty("hibernate.max_fetch_depth", "4");
//
//        return properties;
//    }
//}
//
